package com.xiaobingby.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xiaobingby.common.base.BaseController;
import com.xiaobingby.common.result.JsonResult;
import com.xiaobingby.controller.view.DataTables;
import com.xiaobingby.entity.QueryCondition;
import com.xiaobingby.entity.Role;
import com.xiaobingby.entity.User;
import com.xiaobingby.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author XiaoBingBy
 * @since 2017-07-23
 */
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService iUserService;

    @RequestMapping("/list")
    public String list( Model model ) {
        return "/admin/user/list";
    }

    @ResponseBody
    @RequestMapping("/getUserList")
    public DataTables<User> getUserList(QueryCondition query) {
        Page<User> page = new Page<User>(query.getStart()/query.getLength()+1, query.getLength());
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        if (query.getKeyword() != null)
            wrapper.like("username", query.getKeyword().trim());
        Page<User> userPage = iUserService.selectPage(page, wrapper);
        for (User item:userPage.getRecords()) {
            item.setPassword(null);
            item.setSalt(null);
        }
        DataTables<User> result = new DataTables<User>();
        result.setDraw(query.getDraw());
        result.setRecordsTotal(userPage.getTotal());
        result.setRecordsFiltered(userPage.getTotal());
        result.setData(userPage.getRecords());
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/save")
    public JsonResult save(User user) {
        if (user.getId() == null) {
            return iUserService.insert(user) ? renderSuccess("添加成功") : renderError("添加失败");
        } else {
            return iUserService.updateById(user) ? renderSuccess("修改成功") : renderError("修改失败");
        }
    }

    @ResponseBody
    @RequestMapping("/delete")
    public Object delete(@RequestParam(value = "id", required = false) Integer id) {
        return iUserService.deleteById(id) ? renderSuccess("删除成功") : renderError("删除失败");
    }

}
